# -*- encoding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
#    $Id$
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

import time

import wizard
import netsvc
import pooler
from osv.orm import browse_record

from tools.misc import UpdateableStr,UpdateableDict

from osv import osv, fields

Form_Warning = '''
<form string="KDVN Warning">
    <separator string='You have to select expenses having the same state !' colspan="4"/>
</form>'''

#Form_Warning4 = '''
#<form string="KDVN Warning">
#    <separator string='You have to select expenses having the same type either EN or IN' colspan="4"/>
#</form>'''

Form_Warning2 = '''
<form string="KDVN Warning">
    <separator string="Batch Work-flow doestn't work with status of Rejected; Waiting for Payment and Paid !" colspan="4"/>
</form>'''

Form_Warning3 = '''
<form string="KDVN Warning">
    <separator string="Payment number must be valid !" colspan="4"/>
</form>'''

Fields=UpdateableDict()
Prepair_Form=UpdateableStr()
pts_ids = []
curr_state =''
step = 0
chk_type = ''

class wizard_batch_workflow(wizard.interface):
    #def action_expense_create_payment(self, cr, uid, ids, *args):
    
    def _check(self, cr, uid, data, context):
        global pts_ids, curr_state,chk_type
        ids =[]
        try:
            ids = data['ids']
        except:
            ids = [data['id']]
        
        pts_ids = ids
        
        rop_ids = ",".join(map(str,ids))
        
        cr.execute("Select distinct state from kdvn_request_of_payment where coalesce(paymentno,'')='' and id in (%s)" % rop_ids)
        if cr.rowcount>=1:
            return 'warning3'
        
       # cr.execute("Select distinct substring(trim(paymentno) from 1 for 2) from kdvn_request_of_payment where id in (%s)" % rop_ids)
        #if cr.rowcount>1:
         #   return 'warning4'
        
        cr.execute("Select distinct state from kdvn_request_of_payment where id in (%s)" % rop_ids)
        
        if cr.rowcount>1:
            return 'warning1'
        else:
            curr_state=cr.fetchone()[0]
            
            cr.execute("Select distinct substring(trim(paymentno) from 1 for 2)  from kdvn_request_of_payment where id in (%s)" % rop_ids)
            chk_type =cr.fetchone()[0]
            if curr_state in ['cancel','paid']:
                return 'warning2'
            else:
                return 'next'
            
    def _prepair_form(self, cr, uid, data, context):
        global pts_ids, curr_state, step, chk_type
        Fields['date']={'string':'Date Submit to Accounting Department','type':'date','default': lambda *a:time.strftime('%Y-%m-%d')}
          
        #Fields['date_batch']={'string':'Batch Date','type':'date','default': lambda *a:time.strftime('%Y-%m-%d')}
        
       # Fields['type_batch']={'string':'Type','type':'selection','selection':eval("[('next_step','Next Step'),('from_site','Input From Site Date'),('to_pro_manager','To Procurement Manager Date')]")}
        Prepair_Form.string= ''
        if curr_state=='draft':
            step = 1
            lbl='Process-->Waiting for payment: &lt;Proceed&gt;'
            Prepair_Form.string='''<?xml version="1.0"?>
                    <form string="Batch Process" colspan="4">
                        <group colspan="4">
                            <separator string="'''+lbl+'''" colspan="4"/>
                        </group>
                        <group>
                            <field colspan="2" name="date" required='1'/>
                        </group>
                    </form>'''
        elif curr_state=='completed':
            step = 2
            lbl='Waiting for payment-->Paid: &lt;Payment&gt;'
            Prepair_Form.string='''<?xml version="1.0"?>
                    <form string="Batch Process" colspan="4">
                        <group colspan="4">
                            <separator string="'''+lbl+'''" colspan="4"/>
                        </group>
                        <group>
                            <field colspan="2" string='Date Payment' name="date" required='1'/>
                        </group>
                    </form>'''
       
        return {}
    
    def _batch_workflow(self, cr, uid, data, context):
        global pts_ids
        date_get_from_form = data['form']['date']
        pool = pooler.get_pool(cr.dbname)
        rop_obj = pooler.get_pool(cr.dbname).get('kdvn.request.of.payment')
        if step==1:
            rop_obj.write(cr,uid,pts_ids,{'date_of_submit_to_accounting':date_get_from_form})
            rop_obj.action_payment_done(cr,uid,pts_ids,context)
            wf_service = netsvc.LocalService("workflow")
            for pr_id in pts_ids:
                try:
                    wf_service.trg_delete(uid, 'kdvn.request.of.payment', pr_id, cr)
                except:
                    pass
        else:
            kp_obj = pooler.get_pool(cr.dbname).get('kdvn.payment')
            for rop_obj in rop_obj.browse(cr,uid,pts_ids):
                new_id = kp_obj.create(cr,uid,{'payment_id':rop_obj.id},{'payment_id':rop_obj.id,
                                                                         'payment_amount':rop_obj.total,
                                                                         'currency':rop_obj.currency_id.id})
        
        return {}
        
    states = {
              'init': 
                      {
                       'actions': [],
                       'result': {'type': 'choice','next_state':_check}},
              'warning1': 
                      {
                        'actions': [],
                        'result': {
                                    'type': 'form','arch': Form_Warning,'fields':{},
                                    'state': [('end', '_Ok', 'gtk-ok', True)]}},
              'warning2': 
                      {
                        'actions': [],
                        'result': {
                                    'type': 'form','arch': Form_Warning2,'fields':{},
                                    'state': [('end', '_Ok', 'gtk-ok', True)]}},
              'warning3': 
                      {
                        'actions': [],
                        'result': {
                                    'type': 'form','arch': Form_Warning3,'fields':{},
                                    'state': [('end', '_Ok', 'gtk-ok', True)]}},
              'next': 
                      {
                        'actions': [_prepair_form],
                        'result': {
                                   'type': 'form','arch': Prepair_Form,'fields':Fields,
                                   'state': 
                                            [('end', '_Cancel','gtk-cancel'),
                                             ('finish', '_Ok', 'gtk-ok', True),]}},
              'finish': 
                      {
                        'actions': [_batch_workflow],
                        'result': {
                                   'type': 'state',
                                   'state':'end'}},
              }
wizard_batch_workflow("kdvn.pts.batch.workflow")

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

